<template>
  <v-dialog
    persistent
    class="home-receive-dialog"
    v-model="visible"
    max-width="540px"
  >
    <v-card class="bg-white p-5 m-6">
      <div
        class="
          dialog-header
          text-[#736b7d]
          font-medium
          flex
          justify-between
          pb-9
        "
      >
        <span class="title text-xl">领取今天奖励</span>
        <v-icon
          color="gray darken-2"
          class="text-gray-400"
          @click.stop="closeDialog"
        >
          mdi-close
        </v-icon>
      </div>
      <div class="content">
        <div v-if="amount" class="part rounded-md p-5 mb-2">
          <p class="text-[#736B7D] text-base">
            太棒了！你刚刚获得了今天的奖励 {{amount}} SDAO可用余额 {{balance}} SDAO
          </p>
        </div>
        <div v-else class="part rounded-md p-5 mb-2">
          <p class="text-[#736B7D] text-base mb-3">
            哈哈，别耍赖哟，时间不足24小时，下次领奖时间：{{nextTime}}
          </p>
          <p class="text-[#736B7D] text-base mb-3">
            让你的朋友知道 “Shark DAO” 将下面链接发送给他们，以赚取更多SDAO。
          </p>
          <p class="text-[#736B7D] text-base">
            <span>邀请链接：</span>
            <span class="text-[#2B6EEF]">
              {{shareUrl}}
            </span>
          </p>
        </div>
        <div v-if="dcFlag" class="part rounded-md p-5 mb-2">
          <p>加入DC服务器获取更多资讯…</p>
          <v-btn
            class="w-full text-base mt-4"
            variant="outlined"
            color="#2B6EEF"
            @click="toUrl(dcUrl)"
          >
            查看群组
          </v-btn>
        </div>
        <div v-else class="part rounded-md p-5 mb-2">
          <p>绑定DC获得更多奖励…</p>
          <v-btn
            class="w-full text-base mt-4"
            variant="outlined"
            color="#2B6EEF"
            @click="bindDC"
          >
            绑定Discord
          </v-btn>
        </div>
        <div v-if="tgFlag" class="part rounded-md p-5">
          <p>加入TG服务器获取更多资讯…</p>
          <v-btn
            class="w-full text-base mt-4"
            variant="outlined"
            color="#2B6EEF"
            @click="toUrl(tgUrl)"
          >
            查看群组
          </v-btn>
        </div>
        <div v-else class="part rounded-md p-5">
          <p>绑定TG获得更多奖励…</p>
          <v-btn
            class="w-full text-base mt-4"
            variant="outlined"
            color="#2B6EEF"
            @click="bindTG"
          >
            绑定Telegram
          </v-btn>
        </div>
      </div>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { toRefs, ref } from 'vue';
import UserStore from '@/store/UserStore';
import { bindSocialAccountApi } from '@/api/system/user';
import Dialog from '@/components/dialog/dialog';
import { useI18n } from 'vue-i18n';
import axios from 'axios';

const userStore = UserStore();
const { t } = useI18n();

let emit = defineEmits<{
  e: 'close';
  value: boolean;
}>();
let props = defineProps<{
  visible: boolean;
  infoData: object | null
}>();

let { visible, infoData } = toRefs(props);

let { tgFlag, dcFlag, amount, balance, shareUrl, tgUrl, dcUrl, nextTime } = infoData

let closeDialog = () => {
  emit('close', false);
};

let toUrl = (url) => {
    window.open(url)
};

let oauthWin: any = null;
const previousUrl = null;
const flag = ref<boolean>(false);


/* Make a function to give us configuration for the Discord API */
function make_config(authorization_token) {
  // Define the function
  return {
    // Define "data"
    headers: {
      // Define "headers" of "data"
      authorization: `Bearer ${authorization_token}`, // Define the authorization
    },
  }; // Return the created object
}


const discordAuthorize = async (code: string) => {
  if (code === '') {
    Dialog(t('message.system.bind.dcCode'));
    return;
  }
  if (flag.value === true) {
    return;
  }
  try {
    const tokenResponse = await axios.postForm(
      'https://discord.com/api/oauth2/token',
      {
        client_id: '999165256309944330',
        client_secret: 'vTxV9wUDZN82RoCQTkMD6QDgiKnhiN0x',
        grant_type: 'authorization_code',
        redirect_uri: 'https://sdao.win/profile',
        scope: 'identify',
        code: code + '',
      },
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );
    console.log('token:', tokenResponse.data.access_token);
    if (tokenResponse.data.access_token) {
      await axios
        .get(
          'https://discord.com/api/users/@me',
          make_config(tokenResponse.data.access_token)
        )
        .then(response => {
          console.log('discord user resp:', response.data);
          console.log('username:', response.data.username);
          const username =
            response.data.username + '#' + response.data.discriminator;
          const id = response.data.id;
          bindSocialAccountApi({
            accountId: id,
            accountName: username,
            type: 1,
          })
            .then((res: any) => {
              console.log('bindSocialApi res:', res);
              Dialog(t('message.system.bind.success'));

              const userInfo = {
                ...userStore.userInfo,
                dcId: res,
              };
              userStore.setUserInfo(userInfo);
              flag.value = true;
            })
            .catch((err: any) => {
              console.log('bind social err:', err);
            });
        })
        .catch(err => {
          console.log('get my information from discord err:', err);
        });
    } else {
      Dialog(t('message.system.bind.fail'));
    }
  } catch (e) {
    console.log('get token from discord err:', e);
  }
};

const receiveMessage = async event => {
  if (event.origin !== import.meta.env.VITE_DOMAIN) {
    return;
  }
  const { data } = event;
  console.log('event data:', data);
  if (typeof data === 'string' && data.includes('code=')) {
    await discordAuthorize(data.substring(6));
    oauthWin.close();
    emit('update:is-bind-dialog-open', false);
    // location.reload()
  }
};

const bindTG = () => {
  console.log('enter bind tg');
  // @ts-ignore
  window.Telegram.Login.auth(
    { bot_id: '5547505264', request_access: 'write', embed: 1 },
    data => {
      console.log('telegram res:', data);
      bindSocialAccountApi({
        accountId: data.id,
        accountName: data.username,
        type: 2,
      })
        .then((res: any) => {
          console.log('bindSocialApi res:', res);
          Dialog(t('message.system.bind.success'));

          const userInfo = {
            ...userStore.userInfo,
            tgId: res,
          };
          userStore.setUserInfo(userInfo);
        })
        .catch((err: any) => {
          console.log('bind social err:', err);
        });
    }
  );
};

const bindDC = () => {
  window.removeEventListener('message', receiveMessage);
  console.log('enter bind dc');
  const url =
    'https://discord.com/api/oauth2/authorize?client_id=999165256309944330&redirect_uri=https%3A%2F%2Fsdao.win%2Fprofile&response_type=code&scope=identify';
  // window.location.replace(url)

  const newWinHeight = 600;
  const newWinWidth = 600;
  const winWidth = window.screen.availWidth; // 获取屏幕宽度
  const winHeight = window.screen.availHeight; // 获取屏幕高度
  const left = (winWidth - newWinWidth) / 2; // 获取新窗口距离屏幕左侧的位置
  const top = (winHeight - newWinHeight) / 2; // 获取新窗口距离屏幕顶部的位置
  const strWindowFeatures =
    'width=' +
    newWinWidth +
    ',height=' +
    newWinHeight +
    ',left=' +
    left +
    ',top=' +
    top +
    ',toolbar=no,menubar=no,modal=false,alwaysRaised=yes,location=no,status=no';
  if (oauthWin === null || oauthWin.closed) {
    oauthWin = window.open(url, 'newwindow', strWindowFeatures);
    oauthWin.focus();
  } else if (previousUrl !== url) {
    oauthWin = window.open(url, 'newwindow', strWindowFeatures);
    oauthWin.focus();
  } else {
    oauthWin.focus();
  }

  // name:弹出窗口的名字,可不填，用''代替
  // toolbar=no 是否显示工具栏。yes为显示
  // menubar=no 是否显示菜单栏。yes为显示
  // location=no 是否显示地址字段。yes为显示
  // status=no 是否添加状态栏。yes为可以
  // 设置ref属性，优化seo，告诉搜索引擎不对新页面进行爬取
  oauthWin.ref = 'nofollow';
};
</script>

<style lang="scss">
.home-receive-dialog {
  .v-overlay__content {
    width: 100%;
  }
  .content {
    .part {
      border: 1px solid #dadada;
    }
  }
}
</style>